package com.llkj.youdaocar;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.llkj.youdaocar.bean.LoginBean;
import com.llkj.youdaocar.bean.ResponseDataBean;
import com.llkj.youdaocar.httpUtils.AnsynHttpRequest;
import com.llkj.youdaocar.httpUtils.HttpMethod;
import com.llkj.youdaocar.utils.GsonUtil;
import com.llkj.youdaocar.utils.Utils;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends BaseActivity implements AnsynHttpRequest.ObserverCallBack {

    public static final String USER_ID = "user_id";
    @BindView(R.id.llBack)
    protected LinearLayout llBack;//返回按钮布局

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        systemBarTintManager.setStatusBarTintResource(R.color.transparent);
//        MyApplication.getInstance().getSpUtil().put(SpUtil.USER_ID,"1");

        //处理沉浸式状态栏
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) llBack.getLayoutParams();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            layoutParams.topMargin = Utils.dip2px(this,10);
        } else {
            layoutParams.topMargin = Utils.dip2px(this,20);
        }
    }

    @OnClick({R.id.llBack,R.id.llLoginWechat,R.id.llLoginQQ,R.id.tvServiceAgree,R.id.tvPrivateAgree})
    public void onClick(View view){
        Intent intent = null;
        switch (view.getId()){
            case R.id.llBack://返回
                finish();
                break;
            case R.id.llLoginWechat://微信登录
//                IWXAPI  mApi = WXAPIFactory.createWXAPI(this,"",true);
//                if(!mApi.isWXAppInstalled()){
//                    Toast.makeText(this,"对不起,您未安装微信app",Toast.LENGTH_LONG).show();
//                    return;
//                }
                authLogin(2, Wechat.NAME);
                break;
            case R.id.llLoginQQ://qq登录
                authLogin(1, QQ.NAME);
                break;
            case R.id.tvServiceAgree://服务协议
                queryProtocol(3);
                break;
            case R.id.tvPrivateAgree://隐私政策
                queryProtocol(2);
                break;
        }
    }
    private void authLogin(final int type,String platName){
        Platform platform= ShareSDK.getPlatform(platName);
        if(!platform.isClientValid() && Wechat.NAME.equals(platName)){
            Toast.makeText(this,"对不起,您未安装微信客户端",Toast.LENGTH_LONG).show();
            return;
        }
        platform.setPlatformActionListener(new PlatformActionListener(){

            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                PlatformDb platDB = platform.getDb();//获取数平台数据DB
                //通过DB获取各种数据
//                String token = platDB.getToken();
//                String gender = platDB.getUserGender();
                String headUrl = platDB.getUserIcon();
                String uid = platDB.getUserId();
                String nick = platDB.getUserName();
                login(type,nick,uid,headUrl);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {}

            @Override
            public void onCancel(Platform platform, int i) {}
        });
//        platform.removeAccount(true);
//        platform.authorize();
        // true不使用SSO授权，false使用SSO授权
//        platform.SSOSetting(true);
        //获取用户资料
        platform.showUser(null);
    }
    //1：qq 2:wechat
    private void login(int type,String nick,String openid,String headUrl){
        showWaitDialog();
        HttpMethod.login(this,this,nick,openid,String.valueOf(type),headUrl);
    }

    private void queryProtocol(int type){
        showWaitDialog();
        HttpMethod.queryProtocol(this,this,String.valueOf(type));
    }

    @Override
    public void onhttpSuccess(String data, int method) {
        if(method==HttpMethod.HTTP_LOGIN_LOGIN){
            ResponseDataBean<LoginBean> baseBean = GsonUtil.fromJson(data,LoginBean.class);
            LoginBean loginBean = baseBean.getData();
            if(baseBean.getCode()==0){
                String uid = loginBean.getId();
                MyApplication.getInstance().getSpUtil().put(USER_ID,uid);
                Intent intent = new Intent();
                intent.putExtra("uid",uid);
                setResult(RESULT_OK,intent);
                PushAgent mPushAgent = PushAgent.getInstance(this);

                mPushAgent.addAlias(uid, "USER_ID", new UTrack.ICallBack() {
                    @Override
                    public void onMessage(boolean isSuccess, String message) {
                        if(BuildConfig.DEBUG){
                            Log.e("Log","==addAlias=="+message);
                        }
                    }
                });

                finish();
            }
        }else if(method==HttpMethod.HTTP_QUERY_PROTOCOL){
            try {
                JSONObject jsonObject = new JSONObject(data);
                if (jsonObject.has("data")) {
                    JSONObject jsonData = jsonObject.getJSONObject("data");
                    if(jsonData.has("value")){
                        Intent intent = new Intent();
                        intent.putExtra("url",jsonData.optString("value"));
                        startActivity(MainActivity.class,intent);
                    }
                }
            } catch (JSONException e) {
            }
        }
    }

}
